package edu.luc.cs.trull.demo.test;

import java.awt.BorderLayout;
import java.awt.event.ActionEvent;
import java.awt.event.ActionListener;
import java.beans.PropertyChangeEvent;
import java.util.StringTokenizer;

import javax.swing.JFrame;
import javax.swing.JLabel;
import javax.swing.JPanel;
import javax.swing.JScrollPane;
import javax.swing.JTextArea;
import javax.swing.JTextField;

import edu.luc.cs.trull.EmitComponent;
import edu.luc.cs.trull.Util;

/**
 * A GUI-based component used to test a Trull component manually.
 * This component comes up in its own frame.
 * Events are entered in the
 * text field in the form name or name=value or name=value0,value1,...
 */
public class SwingTester extends EmitComponent {

    protected JTextArea output;

    public SwingTester(String name) {
        final JFrame frame = new JFrame(name);
        final JPanel panel = new JPanel();
        final JTextField input = new JTextField(20);

        panel.setLayout(new BorderLayout());
        panel.add(new JLabel("Enter event:"), BorderLayout.WEST);
        panel.add(input, BorderLayout.CENTER);

        output = new JTextArea(6, 80);
        output.setEditable(false);

        input.addActionListener(new ActionListener() {
            public void actionPerformed(ActionEvent evt) {
//                input.setText("");
                if (evt.getActionCommand().length() > 0) {
                    StringTokenizer tokens = new StringTokenizer(evt.getActionCommand(), "=,", false);
                    String label = tokens.nextToken();
                    String[] values = new String[tokens.countTokens()];
                    for (int i = 0; i < values.length; i ++) {
                        values[i] = tokens.nextToken();
                    }
                    PropertyChangeEvent event = 
                        new PropertyChangeEvent(SwingTester.this, label, null, values);
                    output.append("sent: " + Util.toString(event) + "\n");
                    firePropertyChange(event);
                }
            }
        });

        frame.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
        
        frame.getContentPane().add(new JScrollPane(output), BorderLayout.CENTER);
        frame.getContentPane().add(panel, BorderLayout.NORTH);
        frame.pack();
        frame.setVisible(true);
    }

    public void propertyChange(final PropertyChangeEvent evt) {
        if (evt.getSource() != this) {
        	    output.append("rcvd: " + Util.toString(evt) + "\n");
        }
    }
}
